import { reactive, computed, toRefs } from 'vue';
import { ITableParams } from './table.types'
// import { IResponse } from '@/api/types';
import { isValidKey } from '@/utils';
// import settingStore from '@/store/setting';
// import { message } from 'ant-design-vue';
/**
 * 
 * @param request    请求方法
 * @param initParams 初始化默认参数
 * @param callback   回调处理方法
 */
export const useTable = (search: (data: any) => Promise<any>, initParams: object = {}) => {
    //初始参数
    const state = reactive<ITableParams>({
        form: {
            page: 1,
            size: 2
        },
        total: 0,
        startLimit:0,
        loading: false,
        list: [],
        selectionBox: [],
        selectedRowKeys: []
    });
    //分页参数
    let pagination = computed(() => {
        return {
            showSizeChanger: false,
            pageSize: state.form.size,
            current: state.form.page || 1,
            total: state.total || 0,
            onChange: pageChange,
            onShowSizeChange: sizeChange
        }
    });
    //页数变化
    const pageChange = (current: number) => {
        search(current)
        state.selectionBox = []
        state.selectedRowKeys = []
    }
    //页size变化
    const sizeChange = (current: number, size: number) => {
        state.form.size = size;
        search(current)
        state.selectionBox = []
        state.selectedRowKeys = []
    }
    //多选
    let selection = computed(() => {
        return {
            selectedRowKeys: state.selectedRowKeys,
            onChange: onSelectChange
        }
    });
    //多选
    const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
        state.selectedRowKeys = selectedRowKeys;
        state.selectionBox = selectedRows;
    }

    //重置搜索
    const reset = () => {
        for (const key in initParams) {
            if (isValidKey(key, initParams)) {
                state.form.current[key] = initParams[key]
            }
        }
    }

    return {
        ...toRefs(state),
        pagination,
        selection,
        reset
    }
}
